package com.jed.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.jed.R;
import com.jed.adapter.JiCaiAdapter;
import com.jed.entity.JiCai;
import com.jed.util.L;
import com.jed.util.StaticClass;
import com.jed.util.StringUtil;
import com.jed.util.T;
import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 项目名：XMKAPP<br/>
 * 包名：  com.jed.ui<br/>
 * 作者：徐晓辉<br/>
 * 创建日期：2018/11/27 18:05<br/>
 * 描述：集采审核<br/>
 */
public class JiCaiListActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    private ListView lv_jiCaiList;
    private JiCaiAdapter adapter;
    private List<JiCai> list = new ArrayList<>();
    private static final int REQUEST_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jicailist);
        dialog.show();
        initView();
        dialog.dismiss();

    }

    private void initView() {
        lv_jiCaiList = findViewById(R.id.lv_jiCaiList);
        lv_jiCaiList.setOnItemClickListener(this);
        getJiCaiList();
    }

    /**
     * 获取集采数据集合
     */
    public void getJiCaiList() {
        RxVolley.get(StaticClass.JI_CAI_LIST_URL, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                dialog.dismiss();
                L.i("获取的集采数据集合：" + t);
                parseJson(t);
            }
        });
    }

    private void parseJson(String t) {
        Gson gson = new Gson();
        JiCai[] jiCais = gson.fromJson(t, JiCai[].class);
        list = Arrays.asList(jiCais);
        if (list.size() > 0) {
            adapter = new JiCaiAdapter(list);
            lv_jiCaiList.setAdapter(adapter);
        } else {
            T.showShortToast(this.getString(R.string.no_data));
        }
    }



    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        JiCai jiCai = list.get(position);
        Intent intent = new Intent(this, JiCaiActivity.class);
        intent.putExtra("jiCai", StringUtil.toGson(jiCai));
        intent.putExtra("position", position);
        startActivityForResult(intent,REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (REQUEST_CODE == requestCode && JiCaiActivity.RESULT_CODE == resultCode){
            int position = data.getIntExtra("position", -1);
            String s = data.getStringExtra("jiCai");
            JiCai jiCai = new Gson().fromJson(s, JiCai.class);
            list.set(position,jiCai);
            adapter.notifyDataSetChanged();
        }
    }
}